<?php
/**
 * 用户实名信息类
 * Created by PhpStorm.
 * User: 王海东
 * Date: 2018/12/18
 * Time: 16:59
 */

namespace app\common\model;
use think\Db;

class UserReal
{
    private const TAB_NAME = 'user_real';

    /**
     * 添加实名认证
     * @author 王海东
     * @date
     * @param array $data
     * [
     *      user_id     用户uid
     *      user_id     用户姓名
     *      user_id     用户身份证
     * ]
     * @return bool
     * @throws \Exception
     */
    public function add(array $data)
    :bool {
        $insert = [
            'user_id'       => $data['user_id'],
            'name'          => $data['name'],
            'id_num'        => $data['id_num'],
            'create_time'   => date('Y-m-d H:i:s'),
            'status'        => 1
        ];

        try {
            return Db::name(self::TAB_NAME)
                ->insertGetId($insert) ? true : false;

        } catch (\Exception $e) {
            throw new \Exception('实名信息添加失败');
        }
    }

    /**
     * 查询用户实名认证信息
     * @author 王海东
     * @date
     * @param int $user_id  用户id
     * @return array
     * @throws \Exception
     */
    public function find(int $user_id)
    :array {
        try {
            $data = Db::name(self::TAB_NAME)
                    ->field('id,name,status,id_num')
                    ->where('user_id',$user_id)
                    ->find();

            if(!$data) {
                $data = [];
            }

            return $data;

        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }
    }

    /**
     * 修改实名认证信息
     * @author 王海东
     * @date
     * @param int   $user_id    用户id
     * @param array $data
     * [
     *    name    姓名
     *    id_num  身份证
     *    status  0 审核中 1审核成功  2审核失败
     * ]
     * @return bool
     * @throws \Exception
     */
    public function edit(int $user_id,array $data)
    :bool {

        $update = [];

        if (isset($data["name"])) {
            $update["name"]     = $data["name"];
        }
        if (isset($data["id_num"])) {
            $update["id_num"]   = $data["id_num"];
        }
        if (isset($data["status"])) {
            $update["status"]   = $data["status"];
        }

        try {
            return Db::name(self::TAB_NAME)
              ->where('user_id',$user_id)
              ->update($update) ? true :false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}